﻿using DreamCMS.Entity;
using DreamCMS.WebCore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DreamCMS.BLL.Common
{
    public class LoginHelper
    {
        private static readonly string userInfoCookieName = "admin";  //在使用RequestHelper类的时候会给cookie名自动加上本系统的前缀，请注意！所以此处不需要加cookie前缀。
        /// <summary>
        /// 当前客户cookie中的userId
        /// </summary>
        public static long CurrentUserId
        {
            get
            {
                string userId = string.Empty;
                HttpCookie cookie = RequestHelper.GetCookie(userInfoCookieName);
                if (cookie == null)
                {
                    return 0;
                }
                userId = cookie.Values["userid"];
                long luserId = StringHelper.StrToUInt32(userId, 0);
                return luserId;
            }
        }


        /// <summary>
        /// 通过客户端cookie的UserID初步判断是否达到初步登陆验证的要求。
        /// </summary>
        public static bool IsIdLogin
        {
            get
            {
                if (CurrentUserId > 0)
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 用户登录成功，写登录成功的用户信息到客户端cookie
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码（会加密）</param>
        /// <param name="expires">（cookie保存时间---分钟数）</param>
        /// <returns></returns>
        public static bool WriteUserInfoCookie(long userId, string userName, string password, int expires)
        {
            HttpCookie nowCookie = RequestHelper.GetCookie(userInfoCookieName);
            if (nowCookie == null)
            {
                nowCookie = new HttpCookie(ConfigHelper.SitePrefix + userInfoCookieName);
            }
            if (expires > 0)
            {
                nowCookie.Values["expires"] = expires.ToString();
                nowCookie.Expires = DateTime.Now.AddMinutes(expires);
            }
            nowCookie.Values["userid"] = userId.ToString();
            nowCookie.Values["username"] = StringHelper.UrlEncode(userName);
            nowCookie.Values["key"] = Encryption.GetMd5ConfigHash(userId + StringHelper.UrlEncode(userName) + password, 32);

            ServerHelper.SetCookie(nowCookie);
            return true;
        }


        /// <summary>
        /// 获取当前用户Cookie中保存的用户名(前提是初步登陆认证通过才获取)
        /// </summary>
        public static string CurrentUserName
        {
            get
            {
                string username = string.Empty;
                if (IsIdLogin)
                {
                    HttpCookie cookie = RequestHelper.GetCookie(userInfoCookieName);
                    username = StringHelper.UrlDecode(cookie.Values["username"]);
                }
                return username;
            }
        }

        /// <summary>
        /// 获取当前用户Cookie中保存的用户Key（前提是初步认证通过才获取）
        /// </summary>
        public static string CurrentUserKey
        {
            get
            {
                string key = string.Empty;
                if (IsIdLogin)
                {
                    HttpCookie cookie = RequestHelper.GetCookie(userInfoCookieName);
                    key = StringHelper.UrlDecode(cookie.Values["key"]);
                }
                return key;
            }
        }
        /// <summary>
        /// 清除用户登录信息的cookie（当用户cookie登录key失效或服务器上不存在该用户或账户停用时）
        /// </summary>
        /// <returns></returns>
        public static bool RemoveUserCookie()
        {
            HttpCookie nowCookie = RequestHelper.GetCookie(userInfoCookieName);
            if (nowCookie == null)
            {
                nowCookie = new HttpCookie(ConfigHelper.SitePrefix + userInfoCookieName);
            }
            nowCookie.Values.Clear();
            nowCookie.Expires = DateTime.Now.AddYears(-1);
            ServerHelper.SetCookie(nowCookie);
            return true;
        }


        public static bool IsRealLogin(ref string msg)
        {
            if (!LoginHelper.IsIdLogin) //初步检查都不通过肯定需要重新登录
            {
                return false;
            }
            else //初步检查通过后，要进行key的深入检查才能决定该用户是否是真正登录
            {
                UserInfo user = UserManager.GetOneUser(LoginHelper.CurrentUserId);
                //用户是否存在
                if (user == null)
                {
                    LoginHelper.RemoveUserCookie();
                    msg = "用户已删除，请联系系统管理员";
                    return false;
                }
                //用户key是否正确
                if (LoginHelper.CurrentUserKey != Encryption.GetMd5ConfigHash(user.Userid + user.UserName + user.Password, 32))
                {
                    LoginHelper.RemoveUserCookie();
                    return false;
                }
                //用户是否处于暂停状态
                if (user.Status == 0)
                {
                    msg = "用户已停用，请联系系统管理员";
                    RemoveUserCookie();
                    return false;
                }
                //TODO:根据用户的Type类型来遍历后台页面的访问权限控制。
            }
            return true;
        }
    }
}
